<template>
	<view class="uni-tab-bar" id="uni-tab-bar" :style="{height: height}" >
		<view>
			 <slot name="header"/>
		</view>
		<view v-if="tabItems.length==1"></view>
		<scroll-view v-else-if="tabScroll" id="tab-bar" class="uni-swiper-tab" scroll-x :scroll-left="scrollLeft" >
			<view v-for="(tab,index) in tabItems" :key="tab.ID" :class="['swiper-tab-list',tabIndex==index ? 'active' : '']" :id="'tab' + tab.ID"
			 :data-current="index" @click="tapTab(index)">{{tab.Name}}{{tab.Count!=undefined && tab.Count!=0 ? '(' + tab.Count + ')' : ''}}</view>
		</scroll-view>
		<view v-else>
			<uni-segmented-control :current="tabIndex" :values="tabItems" v-on:clickItem="tapTab" :styleType="tabStyleType" :activeColor="tabActiveColor">
			</uni-segmented-control>
		</view>
		
        <head-filter v-if="filterItems.length>0" :items="filterItems" @change="changeFilter"></head-filter>
		<template v-if="listItems">
			<scroll-view v-if="listItems.length==1" v-for="(item,index1) in listItems" :key="index1" :scroll-into-view="scrollIntoView" :scroll-top="scrollTop" class="list" scroll-y :scroll-x="scrollX" @scrolltolower="loadMore(index1)">
				<view>
					<slot name="list" :tabItem="item" :pageItem="pageItem" />
				</view>
				<view class="uni-tab-bar-loading" v-if="item.showLoading">
					<uni-load-more :status="item.status" :contentText="loadingText"  style="height: auto;"></uni-load-more>
				</view>
				<view>
					<slot name="bottom"/>
				</view>
			</scroll-view>
			<swiper v-if="listItems.length>1" :current="tabIndex" class="swiper-box" duration="300" @change="changeTab" >
				<swiper-item v-for="(item,index1) in listItems" :key="index1">
					<scroll-view :scroll-into-view="scrollIntoView" :scroll-top="scrollTop" class="list" scroll-y :scroll-x="scrollX" @scrolltolower="loadMore(index1)">
						<view>
							<slot name="list" :tabItem="item" :pageItem="pageItem" />
						</view>
						<view class="uni-tab-bar-loading" v-if="item.showLoading">
							<uni-load-more :status="item.status" :contentText="loadingText" :search="search" style="height: auto;"></uni-load-more>
						</view>
						<view>
							<slot name="bottom"/>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</template>
	</view>
</template>

<script>
	import uniSegmentedControl from '@/components/uni-segmented-control/uni-segmented-control.vue'
	import uniLoadMore from '../uni-load-more/uni-load-more.vue';
	import headFilter from '@/components/uni-z/head-filter.vue'

	var filterArray = [],filter; //筛选项
	var isClickTab = false;
	
	export default {
		components: { uniSegmentedControl, uniLoadMore,headFilter},
		name: 'navbar-list',
		props: {
			scrollX:{
				type: [Boolean],
				default: false
			},
			listHeight:{
				type: [String],
				default: ""
			},
			moreMargin:{
				type: [Boolean],
				default: false
			},
			noItem:{
				type: [Boolean],
				default: false
			},
			search:{
				type: [Boolean],
				default: false
			},
			isBootom:{
				type: [Boolean,String],
				default: false
			},
			bottom:{
				type: [Number,String],
				default: 0
			},
			scrollIntoView:{
				type: String,
				default: ''
			},
			tabScroll: { //是否为滚动tab
				type: [String, Boolean],
				defalut: false
			},
			tabActiveColor:{
				type: String,
				default: '#007aff'
			}, 
			tabStyleType:{
				type: String,
				default: 'text'
			},
			pageItem:{
				type: Object,
				default: undefined
			},
			loadingInfo:{
				type: Object,
				default: undefined
			},
			initIndex:{
				type: Number,
				default: 0
			},
			tabName:{
				type: String,
				default: "Type"
			},
			tabItems: {
				type: Array,
				default: function(e) {
				    return [{ID:'',Name:'默认选项'}]
				}
			},
			filterItems:{
				type: Array,
				default: function(e) {
				    return []
				}
			},
			url:{
				type: String,
				default: ""
			},
			urlType:{
				type: String,
				default: "get"
			},
			urlData:{
				type: Object,
				default: function(e) {
				    return {}
				}
			}
		},
		watch: {
		   initIndex(newV,oldV) {
			  
		   },
		   url(newV,oldV) {
			  this.httpUrl = newV;
			  console.log(this.httpUrl);	
		   	 
		   }
		},
		data() {
			return {
				curDate:undefined,
				httpUrl:"",
				scrollTop: 0,
				scrollLeft: 0,
				tabIndex: -1,
				height:"100%",
				listItems:undefined,
			}
		},
		created() {
			filterArray = [];
			filter = undefined; 
			this.httpUrl = this.url;
		},
		computed: {
			loadingText() {
				return {
			    	contentdown: (this.loadingInfo && this.loadingInfo.contentdown ? this.loadingInfo.contentdown : "上拉显示更多"),
			    	contentrefresh: (this.loadingInfo && this.loadingInfo.contentrefresh ? this.loadingInfo.contentrefresh :"正在加载..."),
			    	contentnomore: (this.loadingInfo && this.loadingInfo.contentnomore ? this.loadingInfo.contentnomore :"没有更多了"),
			    	contentnodata: (this.loadingInfo && this.loadingInfo.contentnodata ? this.loadingInfo.contentnodata :"暂无相关数据"),
					contentsearch: '未搜索到相关消息哦'
			    };
			}
		},
		mounted(){
			var th = this;
		    //filterArray = [];
		    //filter = undefined;
		    let ary = [];
		    let len = this.tabItems.length;
		    for (let i = 0, length = len; i < length; i++) {
		    	let aryItem = {
		    		first:true,
		    		index:i,
					value:this.tabItems[i].ID,
					showLoading: this.tabItems[i].HideLoading ? false : true,
		    		status: "more",
		    		//pageItem:this.pageItem,
		    		data: []
		    	};
		    	ary.push(aryItem);
		    }
		    this.listItems = ary;
		    
		    var bottomH = parseInt(this.bottom);
		    if(bottomH==0 && this.isBootom)
		    {
		    	bottomH = 56;
		    }

		    //this.height = (this.$common.getWindow().windowHeight - bottomH) + "px";
			if(this.listHeight==""){
				setTimeout(function(){
					const query = uni.createSelectorQuery().in(th);
					query.select('#uni-tab-bar').boundingClientRect(data => {
						th.height = (th.$common.getWindow().windowHeight - (data==null ? 0 : data.top) - bottomH) + "px";
						//console.log(th.height)
						//console.log(th.$common.getWindow().windowHeight)
					}).exec();
				},100)
			}else{
				th.height = this.listHeight;
			}
			
		    if(this.tabItems.length==1)
		    {
		    	this.tapTab(this.initIndex);
		    	this.addData();
		    }else{
		    	if(this.initIndex>-1) {
		    		this.tapTab(this.initIndex);
					this.addData(this.initIndex);
					
					// #ifndef H5
					// #endif
		    	}
		    }	
		},
		methods: {
			changeFilter(filterOptions){
				//改变条件，重新搜索
			    filter = "";
				var newFilterArray = filterArray.slice();

				var isExist = false;
				filterOptions.filterArray.forEach(function(filterItem,filterIndex){
					isExist = false;
					filterArray.forEach(function(item,index){
						if(item.name===filterItem.name)
						{
							isExist = true;
							newFilterArray[index] = filterItem;
						}
					});
					if(!isExist) newFilterArray.push(filterItem);
				});

				newFilterArray.forEach(function(item,index){
					filter = filter + (filter==="" ? "":",") + '"' + item.name + '"' + ':"' + item.value + '"';
				});
				filterArray = newFilterArray;
				filter = JSON.parse("{" + filter + "}");
				if(filterOptions.load) this.addData();
			},
			loadMore(e) {
				this.addData(e);
			},
			refresh(index){
				setTimeout(()=>{
					//清空数据
					if(this.listItems)
					{
						var th = this;
						var initList = function(i){
							th.listItems[i].first = true;
							th.listItems[i].status = "more";
							th.listItems[i].data = [];
						}
						if(index==undefined){
							let len = this.tabItems.length;
							for (let i = 0, length = len; i < length; i++) {
								initList(i);
							}
						}else{
							initList(index);
						}
						this.addData(this.tabIndex);
					}
				},100)
			},
			getData(tabIndex,listIndex){
			    return this.listItems[tabIndex].data[listIndex];
			},
			pushData(tabIndex,item){
				if(this.listItems[tabIndex].data.length==0){
					this.refresh();
				}else{
					this.listItems[tabIndex].data.splice(0,0,item);
					if(this.listItems[tabIndex].status=="no-data"){
						this.listItems[tabIndex].status = "no-more";
					}
				}               
			},
			deleteData(tabIndex,listIndex){
				this.listItems[tabIndex].data.splice(listIndex,1);
			},
			updateData(tabIndex,listIndex,item){
				if(this.listItems){
					this.$set(this.listItems[tabIndex].data,listIndex,item);	
				}
			},
			checkData(listIndex,key){
			    key = (key==undefined ? "FormInfo":key);
				var info = this.$common.getStorage(key);

				if(info){
					switch(info.EditType)
					{
						case "a":
						    this.pushData(0,info);
						    break;
						case "u":
						    this.updateData(0,listIndex,info);
						    break;
						case "d":
					  	    this.deleteData(0,listIndex);
							break;
					}
					// #ifdef MP-WEIXIN
					//解决微信小程序不刷新数据问题
					this.curDate = new Date();
					// #endif
					this.$common.removeStorage(key);
				}
			},
			addData(e) {
				var vueTh = this;
				if(e==undefined || e==null) {
					e = 0;
					vueTh.listItems[e].first = true;
				}
				
				if(vueTh.listItems[e].first)
				{
					//第一次搜索清空数据
					vueTh.listItems[e].status = "loading";
					vueTh.listItems[e].data = [];
				}
				if(vueTh.listItems[e].status=='no-data' || vueTh.listItems[e].status=='no-more')
				{
					return;
				}
				this.listItems[e].status = "loading";
				var loadData = function(data,callBack){
					if(data && data.length>0)
					{
						data.forEach(function(item, index, array) {
							vueTh.listItems[e].data.push(item);
						});
						if(data.length % 10 > 0)
						{
							vueTh.listItems[e].status = "no-more";	
						}else if(data.length==10){
							vueTh.listItems[e].status = "no-more";	
						}else{
							vueTh.listItems[e].status = "more";	
						}
					}else{
						//停止滚动条
						if(vueTh.listItems[e].data.length==0)
						{
							//没有相关数据
							vueTh.listItems[e].status = "no-data";	
						}else{
							//数据加载完
							vueTh.listItems[e].status = "no-more";	
						}
					}
					if(callBack) callBack(vueTh.listItems[e].data);
				};
				var extendData;
				if(this.$parent.$parent.getUrlData) extendData = this.$parent.$parent.getUrlData();
				
				var urlData = JSON.parse(JSON.stringify(this.urlData))
				urlData = Object.assign(urlData, (filter==undefined ? {} : filter),(extendData==undefined ? {} : extendData));
				
			    if(this.url==""){
					this.$emit('listData',
					{ 
						tab:this.tabItems[e],
						index:e,
						first:vueTh.listItems[e].first,
						filter:urlData,
						success:function(data,callBack){
							loadData(data,callBack);
						}
					});
				}else{
					if(!this.tabItems[e]) return;
					urlData[this.tabName] = this.tabItems[e].ID;
					var pageOptions = {
						id: "list" + this.tabItems[e].ID,
						ajaxOptions: {
							pageMode: "page",
							data: urlData,
							type: this.urlType,
							first: vueTh.listItems[e].first,
							url: vueTh.url
						},
						success:function(data){
							if(data.list){
								loadData(data.list);
							}if(data.rows){
								loadData(data.rows);
							}else{
								loadData(data);
							}
						}
					}
					vueTh.$common.initPage(pageOptions);
				}
				
				if(vueTh.listItems[e].first) vueTh.listItems[e].first = false;
			},
			async changeTab(e) {
				let curTab = e.detail.current;

				if (!isClickTab && (this.tabScroll || this.tabScroll=='true'))
				{
					//如果是切换swiper 设置tab滚动位置
					let tabBar = await this.getElSize("tab-bar"),
						tabBarScrollLeft = tabBar.scrollLeft;
					let width = 0;
				
					for (let i = 0; i < curTab; i++) {
						let result = await this.getElSize("tab" + this.tabItems[i].ID);
						width += result.width;
					}
					let winWidth = uni.getSystemInfoSync().windowWidth - 10,
						nowElement = await this.getElSize("tab" + this.tabItems[curTab].ID),
						nowWidth = nowElement.width;
					if (width + nowWidth - tabBarScrollLeft > winWidth) {
						this.scrollLeft = width + nowWidth - winWidth;
					}
					if (width < tabBarScrollLeft) {
						this.scrollLeft = width;
					}
				}
				isClickTab = false;
				if(this.tabIndex!=curTab) this.tabIndex = curTab; 
				
				if(this.listItems[curTab].data.length==0)
				{
					//没有数据第一次加载
					this.addData(curTab);
				}
			},
			getElSize(id) { //得到元素的size
				return new Promise((res, rej) => {
					uni.createSelectorQuery().in(this).select('#' + id).fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			async tapTab(index) { //点击tab-bar
				if (this.tabIndex === index) {
					return false;
				} else {
					if(this.tabScroll || this.tabScroll=='true')
					{
						let tabBar = await this.getElSize("tab-bar"),
							tabBarScrollLeft = (tabBar!=null ? tabBar.scrollLeft : 0); //点击的时候记录并设置scrollLeft
						this.scrollLeft = tabBarScrollLeft;
					}
					isClickTab = true;
					this.tabIndex = index;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uni-tab-bar-loading{
		margin: 30upx;
		padding: 0px;
		padding-bottom: 30upx;
	}
	uni-page-body{
		height:100%;
		font-size:14px;
		line-height:1.8
    }
	.uni-swiper-tab  {
		background-color: #ffffff;
		padding: 0px 5px;
		width: calc(100% - 10px);
		border: 0px;
		position: relative;
	}
	.uni-tab-bar .list-filter {
		width: 750upx;
		height: calc(100% - 44px);
	}
	
	.uni-swiper-tab:after {
		content: " ";
		position: absolute;
		left: 0px;
		bottom: 0;
		right: 0;
		height: 1px;
		border-bottom: 1px solid #c8c7cc;
		-webkit-transform-origin: 0 100%;
		-ms-transform-origin: 0 100%;
		transform-origin: 0 100%;
		-webkit-transform: scaleY(.5);
		-ms-transform: scaleY(.5);
		transform: scaleY(.5);
		color: #c8c7cc;
	}
	.swiper-tab-list{
		width:auto;
		padding: 2px 10px;
	}
	.uni-tab-bar .active{
		background: -webkit-gradient(linear, left top, right bottom, from($uni-theme-color), to($uni-theme-color));
		color: #FFFFFF;
		line-height: 1.7;
		-webkit-border-radius: 18px;
		border-radius: 18px;
		/* padding: 4px 5px; */
		font-size: 14px;
	}
	
	.uni-tab-bar .swiper-box {
		height: calc(100% - 100upx);
	}
	
	/* #ifdef MP-ALIPAY */
	.swiper-tab-list {
		display: inline-block;
	}
	/* #endif */
</style>
